package com.supersit.greensproject.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.supersit.greensproject.Amap.AMap_LocationUtils;
import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.activity.AMapPolygonActivity;
import com.supersit.greensproject.activity.BaseFragment;
import com.supersit.greensproject.adapter.CoordinateListAdapter;
import com.supersit.greensproject.entity.BaseBase;
import com.supersit.greensproject.entity.Coordinate;
import com.supersit.greensproject.utils.NetUtils;
import com.supersit.greensproject.utils.RegularExpressionUtils;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.CustomDialog;
import com.supersit.greensproject.view.ShowDialog;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 数据录入
 * Created by cong on 2016/7/14.
 */
@ContentView(R.layout.fragment_entering_data)
public class EnteringDataFragment extends BaseFragment {
    private Context context;
    @ViewInject(R.id.sp_entering_area)
    private Spinner spArea;
    @ViewInject(R.id.et_entering_data)
    private EditText etCreateDate;
    @ViewInject(R.id.et_entering_base_name)
    private EditText etBaseName;
    @ViewInject(R.id.et_entering_base_address)
    private EditText etBaseAddress;
    @ViewInject(R.id.et_entering_contacts)
    private EditText etContacts;
    @ViewInject(R.id.et_entering_tel)
    private EditText etTel;
    @ViewInject(R.id.et_entering_email)
    private EditText etEmail;
    @ViewInject(R.id.et_entering_proportion)
    private EditText etProportion;//面积
    @ViewInject(R.id.et_business_licence)
    private EditText etBusinessLicence;//营业执照
    @ViewInject(R.id.ib_addCoordinates)
    private ImageButton ibAddCoordinate;//增加坐标
    @ViewInject(R.id.ib_show_polygon)
    private ImageButton ibShowPolygon;//地图显示
    @ViewInject(R.id.btn_save_baseinfo)
    private Button btnSave;
    @ViewInject(R.id.lv_coordinates_list)
    private LinearLayout lvCoordinate;//坐标列表

    private List<Coordinate> coordinates;
    private SimpleDateFormat dateFormater;
    private String areaStr;
    private int baseType;
    private AMap_LocationUtils locationUtils;
    private CoordinateListAdapter coordinateListAdapter;
    private int coordinateCount = 0;
    private String[] areas;
    private boolean isUpdate = false;
    private int updateCoordinateItem = 0;
    private ShowDialog showDialog;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = getActivity();
        initVariable();
        bindListener();
    }

    private void initVariable() {
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                context, R.array.area, R.layout.spinner_text);
        adapter.setDropDownViewResource(R.layout.item_spinner);
        spArea.setAdapter(adapter);
        coordinates = new ArrayList<Coordinate>();
        coordinateListAdapter = new CoordinateListAdapter(context, coordinates);
        areas = getResources().getStringArray(R.array.area);
        areaStr = areas[0];
        // lvCoordinate.setAdapter(coordinateListAdapter);
        // setListViewHeightBasedOnChildren(lvCoordinate);
        dateFormater = new SimpleDateFormat("yyyy-MM-dd");
        showDialog = new ShowDialog(context);
        etCreateDate.setText(dateFormater.format(new Date()).toString());
        Bundle bundle = getActivity().getIntent().getExtras();
        baseType = bundle.getInt("baseType");
        locationUtils = new AMap_LocationUtils(context, getResult);

    }

    private void bindListener() {
        btnSave.setOnClickListener(onClickListener);
        ibAddCoordinate.setOnClickListener(onClickListener);
        ibShowPolygon.setOnClickListener(onClickListener);
        spArea.setOnItemSelectedListener(onItemSelectedListener);
    }

    private AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            areaStr = areas[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_save_baseinfo:
                    if (checkData()) {
                        String createDate = TextUtils.isEmpty(etCreateDate.getText().toString()) ? "" : etCreateDate.getText().toString().trim();
                        String baseName = TextUtils.isEmpty(etBaseName.getText().toString()) ? "" : etBaseName.getText().toString().trim();
                        int areaId = spArea.getSelectedItemPosition();
                        String baseAddress = TextUtils.isEmpty(etBaseAddress.getText().toString()) ? "" : etBaseAddress.getText().toString().trim();
                        String contacts = TextUtils.isEmpty(etContacts.getText().toString()) ? "" : etContacts.getText().toString().trim();
                        String tel = TextUtils.isEmpty(etTel.getText().toString()) ? "" : etTel.getText().toString().trim();
                        String email = TextUtils.isEmpty(etEmail.getText().toString()) ? "" : etEmail.getText().toString().trim();
                        String proportion = TextUtils.isEmpty(etProportion.getText().toString()) ? "" : etProportion.getText().toString().trim();//面积
                        String businessLicence = TextUtils.isEmpty(etBusinessLicence.getText()) ? "" : etBusinessLicence.getText().toString().trim();//自给能力
                        StringBuffer longitudes = new StringBuffer();//经度
                        StringBuffer latitudes = new StringBuffer();//纬度
                        for (int i = 0; i < coordinates.size(); i++) {
                            if (i == (coordinates.size() - 1)) {
                                longitudes.append(coordinates.get(i).getLongitude() + "");
                                latitudes.append(coordinates.get(i).getLatitude() + "");
                            } else {
                                longitudes.append(coordinates.get(i).getLongitude() + ",");
                                latitudes.append(coordinates.get(i).getLatitude() + ",");
                            }
                        }
                        BaseBase base = new BaseBase();
                        base.setCreateDate(createDate);
                        base.setBaseName(baseName);
                        base.setAreaId(areaId);
                        base.setBaseAddress(baseAddress);
                        base.setContacts(contacts);
                        base.setTel(tel);
                        base.setEmail(email);
                        base.setProportion(proportion);
                        base.setBusinessLicence(businessLicence);
                        base.setLongitudes(longitudes.toString());
                        base.setLatitudes(latitudes.toString());
                        //base.setTimeStamp(new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()));
                        base.setType(baseType);
                        base.setIsDelete(1);//1正常 0删除
                        base.setOperationsTatus(1);//操作状态(0：删除；icv1：新增；icv2：修改 -icv1: 正常)
                        DbManager db = XUtilsDbManager.getInstance();
                        try {
                            db.saveBindingId(base);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        //清除控件内容
                        clearEditText();
                        T.showShort(context, R.string.save_ok);
                    }
                    break;
                case R.id.ib_show_polygon:
                    if (coordinates.size() < 3) {
                        T.showShort(context, R.string.base_coordinate_is_null);
                    } else {
                        Intent showPolygoniItent = new Intent(context, AMapPolygonActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("coordinates", (Serializable) coordinates);
                        showPolygoniItent.putExtras(bundle);
                        context.startActivity(showPolygoniItent);
                    }
                    break;
                case R.id.ib_addCoordinates:
                    if (NetUtils.isConnected(context)) {
                        locationUtils.startLocation();
                        ibAddCoordinate.setEnabled(false);
                        showDialog.showLoadingDialog(getString(R.string.locationing));
                    } else {
                        T.showShort(context, R.string.net_not_connected);
                    }
                    break;
            }
        }
    };

    private boolean checkData() {
        boolean flag = false;
        if (TextUtils.isEmpty(etBaseName.getText().toString())) {
            T.showShort(context, R.string.base_name_is_null);
            return flag;
        }
        if (TextUtils.isEmpty(etBaseAddress.getText().toString())) {
            T.showShort(context, R.string.base_address_is_null);
            return flag;
        }
//        if (TextUtils.isEmpty(etContacts.getText().toString())) {
//            T.showShort(context, R.string.base_contacts_is_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etTel.getText().toString())) {
//            T.showShort(context, R.string.base_tel_is_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etProportion.getText().toString())) {
//            T.showShort(context, R.string.base_aera_is_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etBusinessLicence.getText().toString())) {
//            T.showShort(context, R.string.base_business_licence_is_null);
//            return flag;
//        }
        if (null != coordinates && coordinates.size() < 3) {
            T.showShort(context, R.string.base_coordinate_is_null);
            return flag;
        }
        if (!TextUtils.isEmpty(etEmail.getText().toString().trim())) {
            boolean result = RegularExpressionUtils.checkEmail(etEmail.getText().toString().trim());
            if (!result) {
                T.showShort(context, R.string.email_invalid);
                return flag;
            }
        }
        flag = true;
        return flag;
    }

    private AMap_LocationUtils.GetResult getResult = new AMap_LocationUtils.GetResult() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            showDialog.dismissLoadDialog();
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    final double latitude = amapLocation.getLatitude();//获取纬度
                    final double longitude = amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);//定位时间
                    amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    amapLocation.getCountry();//国家信息
                    amapLocation.getProvince();//省信息
                    amapLocation.getCity();//城市信息
                    amapLocation.getDistrict();//城区信息
                    amapLocation.getStreet();//街道信息
                    amapLocation.getStreetNum();//街道门牌号信息
                    amapLocation.getCityCode();//城市编码
                    amapLocation.getAdCode();//地区编码
                    amapLocation.getAoiName();//获取当前定位点的AOI信息
                    if (isUpdate) {
                        if (updateCoordinateItem >= 0) {
                            coordinates.get(updateCoordinateItem).setLatitude(latitude);
                            coordinates.get(updateCoordinateItem).setLongitude(longitude);
                            reapplication(coordinates);
                            ibAddCoordinate.setEnabled(true);
                            isUpdate = false;
                        }

                    } else {
                        CustomDialog dialog;
                        CustomDialog.Builder customBuilder = new CustomDialog.Builder(
                                context);
                        customBuilder
                                .setTitle(R.string.location_affirm)
                                .setMessage("经度:" + longitude + "\n纬度:" + latitude)
                                .setNegativeButton(R.string.ok,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int which) {
                                                //T.showShort(context, "NegativeButton");
                                                Coordinate coordinate = new Coordinate();
                                                coordinate.setLatitude(latitude);
                                                coordinate.setLongitude(longitude);

                                                View view = LayoutInflater.from(context).inflate(R.layout.item_coordinate_list, null);
                                                TextView lon = (TextView) view.findViewById(R.id.tv_item_longinude);
                                                TextView lag = (TextView) view.findViewById(R.id.tv_item_latitude);
                                                TextView num = (TextView) view.findViewById(R.id.tv_item_num);
                                                Button btnRemoveCoordinate = (Button) view.findViewById(R.id.btn_remove_coordinate);
                                                lon.setText("经度" + coordinate.getLongitude() + "");
                                                lag.setText("纬度" + coordinate.getLatitude() + "");
                                                num.setText((coordinateCount + 1) + "");
                                                view.setTag(coordinateCount + 1);
                                                lvCoordinate.addView(view);
                                                coordinates.add(coordinate);
                                                coordinateStatuListener(btnRemoveCoordinate, (Integer) view.getTag());
                                                coordinateCount++;
                                                coordinateListAdapter.setData(coordinates);
                                                coordinateListAdapter.notifyDataSetChanged();
                                                ibAddCoordinate.setEnabled(true);
                                                dialog.dismiss();
                                            }
                                        })
                                .setPositiveButton(R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int which) {
                                                //  T.showShort(context, "PositiveButton");
                                                ibAddCoordinate.setEnabled(true);
                                                dialog.dismiss();
                                            }
                                        });
                        dialog = customBuilder.create();
                        dialog.show();

                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    CustomDialog dialog;
                    CustomDialog.Builder customBuilder = new CustomDialog.Builder(
                            context);
                    customBuilder
                            .setTitle(R.string.location_fail)
                            .setMessage("ErrCode:"
                                    + amapLocation.getErrorCode() + "\n errInfo:"
                                    + amapLocation.getErrorInfo())
                            .setNegativeButton(R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            dialog.dismiss();
                                            ibAddCoordinate.setEnabled(true);
                                        }
                                    });
                    dialog = customBuilder.create();
                    dialog.show();

                }
            } else {
                T.showShort(context, R.string.location_fail);
            }

            locationUtils.stopLocation();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        locationUtils.unRegisterLocationListener();
    }

    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return false;
        }
    };

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    private void clearEditText() {
        // etCreateDate.setText("");
        etBaseName.setText("");
        etBaseAddress.setText("");
        etContacts.setText("");
        etTel.setText("");
        etEmail.setText("");
        etProportion.setText("");//面积
        etBusinessLicence.setText("");//营业执照
        lvCoordinate.removeAllViews();//坐标列表
        coordinateCount = 0;
        coordinates.clear();
    }

    /**
     * 刷新座標
     */
    private void reapplication(List<Coordinate> coordinates) {
        if (null != coordinates && coordinates.size() > 0) {
            lvCoordinate.removeAllViews();
            coordinateCount = 0;
            for (int x = 0; x < coordinates.size(); x++) {
                View view = LayoutInflater.from(context).inflate(R.layout.item_coordinate_list, null);
                TextView lon = (TextView) view.findViewById(R.id.tv_item_longinude);
                TextView lag = (TextView) view.findViewById(R.id.tv_item_latitude);
                TextView num = (TextView) view.findViewById(R.id.tv_item_num);
                Button removeCoordinate = (Button) view.findViewById(R.id.btn_remove_coordinate);
                Coordinate coordinate = coordinates.get(x);
                lon.setText("经度" + coordinate.getLongitude());
                lag.setText("纬度" + coordinate.getLatitude());
                num.setText((x + 1) + "");
                view.setTag(x + 1);
                coordinateStatuListener(removeCoordinate, (Integer) view.getTag());
                lvCoordinate.addView(view);
                //   coordinates.add(coordinate);
                coordinateCount = x;
            }
        }
    }

    /**
     * 刪除或者修改座標狀態監聽
     *
     * @param removeCoordinate
     */
    private void coordinateStatuListener(Button removeCoordinate, final int viewTag) {
        removeCoordinate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(context).setTitle(R.string.remove_coordinate_title)
                        .setMessage(String.format(context.getString(R.string.is_remove_coordinate), viewTag + ""))
                        .setPositiveButton(R.string.update_coordinate, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                updateCoordinateItem = viewTag - 1;
                                isUpdate = true;
                                if (NetUtils.isConnected(context)) {
                                    locationUtils.startLocation();
                                    ibAddCoordinate.setEnabled(false);
                                    showDialog.showLoadingDialog(getString(R.string.locationing));
                                } else {
                                    T.showShort(context, R.string.net_not_connected);
                                }
                            }
                        })
                        .setNegativeButton(R.string.remove_coordinate, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                coordinates.remove(viewTag - 1);
                                reapplication(coordinates);
                            }
                        }).show();
            }
        });
    }
}
